
import 'dart:typed_data';
import 'dart:ui';

import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:image_gallery_saver/image_gallery_saver.dart';
import 'package:qr_flutter/qr_flutter.dart';

class QrCreatePage extends StatefulWidget{
  const QrCreatePage({Key? key}) : super(key: key);

  @override
  State<StatefulWidget> createState() {
    return QrCreateState();
  }

}

class QrCreateState extends State<QrCreatePage> {
  String content = "hello qr";

  FocusNode focusNode = FocusNode();
  @override
  Widget build(BuildContext context) {
    return Material(
      child: Column(
        children: [
          const SizedBox(height: 50),
          GestureDetector(
            onTap: (){
              Navigator.pop(context);
            },
            child: const Align(
              alignment: Alignment.topLeft,
              child: Padding(padding: EdgeInsets.fromLTRB(30, 10, 10, 10),child: Icon(Icons.arrow_back_ios_new),),
            ),
          ),
          const SizedBox(height: 100),
          RepaintBoundary(
            key: _globalKey,
            child: DecoratedBox(//如果要添加居中图片，则使用stack层叠布局在二维码上覆盖一张图片即可
              decoration: const BoxDecoration(color: Colors.white),
              child: QrImage(data: content, size: 200),
            ),
          ),

          Padding(padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 30),
            child: TextField(
              focusNode: focusNode,
              decoration: InputDecoration(hintText: "请输入二维码内容",
                  contentPadding: const EdgeInsets.symmetric(horizontal: 10, vertical: 20),
                  focusedBorder: OutlineInputBorder(borderRadius: BorderRadius.circular(10), borderSide: const BorderSide(color:Colors.green, width: 1)),
                  enabledBorder: OutlineInputBorder(borderRadius: BorderRadius.circular(10), borderSide: const BorderSide(color:Colors.grey, width: 1)),
                  isCollapsed: true
              ),
              onSubmitted: (value){
                setState((){});
                focusNode.unfocus();
              },
              onChanged: (value){
                content = value;
              },
              // onEditingComplete: (){
              //   print("onEditingComplete");
              // },
              // minLines: 1,
              // maxLines: 10,
            ),
          ),

          Row(
            mainAxisAlignment: MainAxisAlignment.spaceEvenly,
            children: [
              ElevatedButton(onPressed: (){setState((){});}, child: const Text("生成二维码")),
              ElevatedButton(onPressed: (){_saveQrImg();}, child: const Text("保存二维码"))
            ],
          )
        ],
      ),
    );
  }

  final GlobalKey _globalKey = GlobalKey();
  Future _saveQrImg() async {
    try {
      RenderRepaintBoundary? boundary =
      _globalKey.currentContext?.findRenderObject() as RenderRepaintBoundary?;
      final image = (await boundary?.toImage(pixelRatio: 3.0));
      final byteData = await (image!.toByteData(format: ImageByteFormat.png));

      Uint8List pngBytes = byteData!.buffer.asUint8List();

      final result = await ImageGallerySaver.saveImage(
          Uint8List.fromList(pngBytes),
          quality: 100,
          name: "${DateTime.now().millisecond}.png");

      if(result != null && result["isSuccess"] == true){
        Fluttertoast.showToast(msg: "保存成功！");
      } else {
        Fluttertoast.showToast(msg: "保存失败！");
      }
    } catch (e) {
      Fluttertoast.showToast(msg: "保存失败！");
    }
    return null;
  }
}